using Admin2505.Application.Common.Interfaces;
using Admin2505.Domain.Entityes.App;
using Admin2505.Domain.Reposoitories;

namespace Admin2505.Application.Services;


public class AuthService
{
    private readonly IRepository<AppUser> _authRepository;

    private readonly IPasswordHasher _passwordHasher;   

    public AuthService(IRepository<AppUser> authRepository, IPasswordHasher passwordHasher)
    {
        _authRepository = authRepository;
        _passwordHasher = passwordHasher;
    }

    //注册
    public async Task<AppUser> RegisterAsync(string userName, string password)
    {
        var users = await _authRepository.GetAllAsync();
        if (users.Any(u => u.Username == userName))
        
            throw new Exception("用户名已存在");
            var salt = _passwordHasher.GenerateSalt();
            var hash = _passwordHasher.HasPassword(password, salt);
            var user = new AppUser ( userName, hash, salt);
            await _authRepository.CreateAsync(user);
            return user;
           
        

        
    }
    //登录
    public async Task<AppUser?> LoginAsync(string userName, string password)
    {
        var users = await _authRepository.GetAllAsync();
        var user = users.FirstOrDefault(u => u.Username == userName);
        if (user == null)
            return null;

         var isValid = _passwordHasher.VerifHashedPassword(user.Password, user.Salt, password);
         return isValid ? user : null;   
    }


}